import 'package:azlistview/azlistview.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/chat_window/chat_view.dart';
import 'package:flutter_ncsjqz_getx/page/rong_im/util/rong_widget.dart';
import 'package:get/get.dart';

import 'address_list_logic.dart';

/// <summary>
/// author：zwb
/// dateTime： 2021/12/11 18:24
/// filePath： lib/page/rong_im/address_list_view.dart
/// desc: 通讯录
/// <summary>
///
class AddressListPage extends StatefulWidget {
  final int? type; /// 0 单聊选择联系人 1群聊选择联系人  2隔离联系人 3群聊踢人
  final String? title; /// 标题
  AddressListPage({this.type, this.title});
  @override
  _AddressListPageState createState() => _AddressListPageState();
}

class _AddressListPageState extends State<AddressListPage> {
  final logic = Get.put(AddressListLogic());

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    logic.loadData();
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<AddressListLogic>(
      builder: (controller) {
        return Scaffold(
          appBar: RongWidget.appBarWidget(title: widget.title ?? "通讯录"),
          backgroundColor: Colors.grey[200],
          body: Column(
            children: [
              headSearch(),
              selectAllAddress(),
              addressList(),
            ],
          ),
          bottomNavigationBar: Offstage(
            child: Container(
              color: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 15,),
              height: 60,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  InkWell(
                    child: Row(
                      children: [
                        logic.friendIds.length == logic.contacts.length ? Icon(Icons.check_circle,color: Colors.green,) :
                        Icon(Icons.radio_button_unchecked,color: Colors.grey,),
                        RongWidget.text(" 全选 "),
                      ],
                    ),
                    onTap: ()=>logic.setAllUser(),
                  ),
                  RongWidget.gradientButton("确定",onTap: logic.friendIds.length == 0 ? null: (){
                    Get.back(result: logic.users);
                  },circular: 40,color: logic.friendIds.length != 0 ? null: Colors.grey),
                ],
              ),
            ),
            offstage: widget.type == 0,
          ),
        );
      },
    );
  }

  @override
  void dispose() {
    Get.delete<AddressListLogic>();
    super.dispose();
  }

  /// 选择所以关注的人 按钮
  Widget selectAllAddress(){
    return Offstage(
      child: InkWell(
        onTap: ()=>logic.setFansUser(),
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 15,vertical: 10),
          child: Row(
            children: [
              logic.fansAllUser ?Icon(Icons.check_circle,color: Colors.green,):Icon(Icons.radio_button_unchecked,color: Colors.grey,),
              RongWidget.text("  所有关注的人"),
            ],
          ),
          color: Colors.white,
        ),
      ),
      offstage: widget.type !=2,
    );
  }

  /// 搜索栏
  Widget headSearch() {
    return Container(
      padding: EdgeInsets.all(15),
      child: RongWidget.rongInput(
        controller: logic.textEditingControllerSearch,
        circular: 5,
        height: 45,
        bgColor: Colors.white,
        prefixIcon: Icon(Icons.search,color: Colors.grey[400],),
        hintText: "搜索好友/群聊名称",
        hintStyle: TextStyle(color: Colors.grey),
        onChanged: (v){
          searchData(v);
        },
      ),
    );
  }

  /// 联系人列表
  Widget addressList() {
    return Expanded(
      child:AzListView(
        data: logic.searchContacts.length > 0 ?logic.searchContacts : logic.contacts,
        itemCount: logic.searchContacts.length > 0 ?logic.searchContacts.length :logic.contacts.length,
        itemBuilder: (BuildContext context, int index) => buildListItem(logic.searchContacts.length > 0 ?logic.searchContacts[index] : logic.contacts[index],index),
        physics: BouncingScrollPhysics(),
        indexBarData: SuspensionUtil.getTagIndexList(logic.searchContacts.length > 0 ?logic.searchContacts : logic.contacts),
        indexBarHeight: 0, // 隐藏右侧abcd筛选
      ),
    );
  }

  /// 搜索
  void searchData(String search){
    // 搜索前清空搜索记录
    logic.searchContacts = [];
    logic.contacts.forEach((element) {
      // 存在某个字段
      if(element.name.contains(search)) logic.searchContacts.add(element);
    });
    logic.handleList(logic.searchContacts);
    logic.update();
  }

  /// azlistview插件 列表头部
  Widget buildHeader() {
    return Container(
      padding: EdgeInsets.all(20),
      alignment: Alignment.center,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          ClipOval(
              child: Image.asset(
                "./assets/images/avatar.png",
                width: 80.0,
              )),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: Text(
              "远行",
              textScaleFactor: 1.2,
            ),
          ),
          Text("+86 182-286-44678"),
        ],
      ),
    );
  }

  /// azlistview插件 左上角分类标题
  Widget buildSusWidget(String susTag) {
    /// 副标题
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 15.0),
      height: logic.susItemHeight,
      width: double.infinity,
      alignment: Alignment.centerLeft,
      child: Text(
        '$susTag',
        textScaleFactor: 1.2,
      ),
    );
  }

  /// azlistview插件 列表子项
  Widget buildListItem(ContactInfo model,index) {
    String susTag = model.getSuspensionTag();
    return Column(
      children: <Widget>[
        Offstage(
          offstage: model.isShowSuspension != true,
          child: buildSusWidget(susTag),
        ),
        Container(
          color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Row(
            children: [
              Offstage(
                child: logic.friendIds.contains(model.ryUserId) ? Icon(Icons.check_circle,color: Colors.green,) :
                Icon(Icons.radio_button_unchecked,color: Colors.grey,),
                offstage: widget.type == 0,
              ),
              Expanded(
                child: ListTile(
                  leading: ClipRRect(
                    borderRadius: BorderRadius.circular(5),
                    child: RongWidget.imgNet('${model.img}',width: 60,height: 60),
                  ),
                  title: Text(model.name),
                  onTap: () {
                    // 进入单聊
                    if(widget.type == 0){
                      Get.to(()=>ChatPage(
                        conversationType: 1,
                        targetId: logic.imUsersListData![index].ryUserId!,
                        title:logic.imUsersListData![index].nickName,
                        userPic: logic.imUsersListData![index].picUrl,
                        friendId: logic.imUsersListData![index].friendId,
                      ));
                      return;
                    }
                    // 群聊、隔离 进行多选操作
                    if(logic.friendIds.contains(model.ryUserId)){
                      logic.friendIds.remove(model.ryUserId);
                      logic.users.remove(model);
                    }else{
                      logic.friendIds.add(model.ryUserId);
                      logic.users.add(model);
                    }
                    logic.update();
                  },
                  // 选择单聊时 左侧间隙为 0
                  contentPadding: EdgeInsets.symmetric(horizontal: widget.type == 0 ? 0:15,vertical: 10),
                ),
              ),
            ],
          ),
        ),
        Container(
          width: Get.width,
          height: 0.5,
          color: Colors.white,
          padding: EdgeInsets.symmetric(horizontal: 15),
          child: Divider(height: 0.5,color: Colors.grey[300],),
        ),
      ],
    );
  }

  /// azlistview插件 右侧滑动筛选器样式
  Decoration getIndexBarDecoration(Color color) {
    return BoxDecoration(
        color: color,
        borderRadius: BorderRadius.circular(20.0),
        border: Border.all(color: Colors.grey[300]!, width: .5));
  }
}